package com.fragrance.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fragrance.model.RightModel;
import com.fragrance.model.RoleModel;
import com.fragrance.model.UserAccountModel;
import com.fragrance.model.UserRoleCfgModel;
import com.fragrance.service.UserService;
import com.fragrance.util.Constants;
import com.fragrance.util.CustomerIDUtil;
import com.fragrance.util.Encrypt;
import com.jfinal.json.Json;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.redis.Redis;

public class UserServiceImpl implements UserService {

	private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	/**
	 * 管理后台登
	 * 编号：1001
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public Map omsLogin(Map map) {
		logger.info("-- begin UserServiceImpl.login,params{}",map);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String account = map.get("account").toString();
		String password = map.get("password").toString();
		List<UserAccountModel> userInfoList = UserAccountModel.me.find("SELECT * from oms_account_main where account_no = ?",account);
		if(null == userInfoList || userInfoList.size() == 0){
			resultMap.put("code","100101");
			resultMap.put("msg","账号或密码错误！");
			return resultMap;
		}
		UserAccountModel userInfo = userInfoList.get(0);
//		String accountNoTo = userInfo.get("account_no");
		//MD5加密
		String passwordTo = userInfo.get("password");
		if(password.equals(passwordTo)){
			//缓存当前用户信息
			String token = Encrypt.MD5(JSON.toJSONString(userInfo), "utf-8");
			resultMap.put("code",Constants.SUCCESS_CODE);
			resultMap.put("msg",Constants.SUCCESS_MSG);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("token", token);
			data.put("userInfo", userInfo);
			resultMap.put("data",data);
			Redis.use("users").setex(token,24 * 60 * 60, Json.getJson().toJson(userInfo));
			logger.info("=============token================"+Redis.use("users").get(token));
			setOmsUserRightInfo(userInfo);
		}else{
			resultMap.put("code","100102");
			resultMap.put("msg","账号或密码错误！");
		}
		logger.info("-- end UserServiceImpl.login=========================");
		return resultMap;
	}

	/**
	 * 运营管理后台-用户登录权限初始化
	 * @param 1002
	 */
	private void setOmsUserRightInfo(UserAccountModel userInfo){
		logger.info("-- begin OmsLoginServiceImpl.setOmsUserRightInfo--"+System.currentTimeMillis());
		//查询用户对应的角色列表信息
		int userId = userInfo.get("id");
		String customerId = userInfo.get("customer_id");
		List<RoleModel> roleList = new ArrayList<RoleModel>();
		try {
			logger.debug("-- call OmsLoginServiceImpl.setOmsUserRightInfo.queryRoleListByUserId userId="+userId);
			roleList = RoleModel.me.find("SELECT cr.id as roleId,cr.role_name AS roleName,"
					+ "cr.role_desc AS roleDesc,cr.create_id AS createId,cr.update_id AS updateId,"
					+ "DATE_FORMAT(cr.create_date,'%Y-%m-%d %T') AS createDate,"
					+ "DATE_FORMAT(cr.update_date,'%Y-%m-%d %T') AS updateDate,cr.STATUS "
					+ "FROM oms_cfg_role cr,oms_cfg_user_role cur "
					+ "WHERE cur.role_id = cr.id AND cur.user_id = ?",userId);
		} catch (Exception e) {
			logger.error("-- error in OmsLoginServiceImpl.setOmsUserRightInfo,errorCode:4015100104,查询登录用户的角色列表信息错误：",e);
			roleList=null;
		}
		if(null!=roleList && roleList.size()>0){
			//从角色列表信息中过滤处角色id列表
			List<Integer> roleIdList = getRoleIdList(roleList);
			//缓存用户的角色id信息
			Redis.use("users").set("ro_"+customerId, roleIdList);
			//根据角色id列表查询出对应的菜单信息
			if(null != roleIdList && roleIdList.size() > 0){
				StringBuffer roleIdListStr = new StringBuffer();
				roleIdListStr.append(roleIdList.get(0));
				for (int i = 1; i < roleIdList.size(); i++) {
					roleIdListStr.append(","+roleIdList.get(i));
				}

				List<RightModel> rightsList = new ArrayList<RightModel>();
				try {
					rightsList = RightModel.me.find("SELECT r.id,r.pid,r.menu_url as menuUrl,"
							+ "r.menu_icon as menuIcon,r.route_url as routeUrl,r.route_flag as routeFlag,"
							+ "r.menu_name as menuName,r.menu_desc as menuDesc,r.route_type as routeType,"
							+ "r.display_order as displayOrder,r.create_id as createId,r.update_id as updateId,"
							+ "DATE_FORMAT(r.create_date,'%Y-%m-%d %T') as createDate,"
							+ "DATE_FORMAT(r.update_date,'%Y-%m-%d %T') as updateDate,r.status "
							+ "from oms_cfg_right r,oms_cfg_role_right rr where rr.right_id=r.id and rr.role_id in ("+roleIdListStr+")");
				} catch (Exception e) {
					logger.error("-- error in OmsLoginServiceImpl.setOmsUserRightInfo,errorCode:4015100105,查询登录用户的菜单列表信息错误："+e);
					rightsList=null;
				}
				if(null != rightsList && rightsList.size() > 0){
					//权限缓存
					Redis.use("users").set("r_" + customerId, rightsList);
					//获取菜单信息
					List<RightModel> menuList = getMenuFromRightList(rightsList);
					//菜单缓存
					Redis.use("users").set("am_" + customerId,Json.getJson().toJson(menuList));
					System.out.println("---------------------"+Redis.use("users").get("am_" + customerId));
					JSONArray topMenu = getTopMenu(customerId);
					if(null != topMenu){
						//缓存一级菜单
						Redis.use("users").set("top_menu_" + customerId, topMenu);
						//缓存所有一级菜单下的子菜单
						for(int i = 0;i< topMenu.size(); i++){
							JSONObject jsonObject = (JSONObject) topMenu.get(i);
							String menuId = jsonObject.get("id").toString();
							int id = Integer.parseInt(menuId);
							Redis.use("users").set("m_"+menuId+"_"+customerId,getChildMenu(id,customerId));
						}
					}
				}
			}
		}
		logger.info("-- end OmsLoginServiceImpl.setOmsUserRightInfo--"+System.currentTimeMillis());
	}


	private JSONArray getChildMenu(int menuId,String customerId){
		logger.info("-- begin OmsLoginServiceImpl.getChildMenu--"+System.currentTimeMillis());
		//从缓存中获取当前登录人的菜单
		String rightsStr = Redis.use("users").get("am_"+customerId);
		JSONArray jsonArray = new JSONArray();
		if(!StringUtils.isBlank(rightsStr)){
			try{
				JSONArray arry = treeMenuList(JSONArray.parseArray(rightsStr),0);
				for (int i = 0; i < arry.size(); i++) {
					JSONObject jsonObject = (JSONObject) arry.get(i);
					if(jsonObject.get("id").toString().equals(menuId+"")){
						jsonArray.add(arry.get(i));
					}
				}
			}catch(Exception e){
				logger.error("-- in OmsLoginServiceImpl.getChildMenu,errorCode:4015100106,获取缓存子菜单信息错误:",e);
			}
		}
		logger.info("-- end OmsLoginServiceImpl.getChildMenu--"+System.currentTimeMillis());
		return jsonArray;
	}
	
	private JSONArray treeMenuList(JSONArray menuList, int parentId) {  
		logger.info("-- begin OmsLoginServiceImpl.treeMenuList--"+System.currentTimeMillis());
		JSONArray childMenu = new JSONArray();  
		for (Object object : menuList) {  
			JSONObject jsonMenu = JSONObject.parseObject(object.toString());  
			int menuId = jsonMenu.getIntValue("id");  
			int pid = jsonMenu.getIntValue("pid");  
			if (parentId == pid) {  
				JSONArray c_node = treeMenuList(menuList, menuId);  
				jsonMenu.put("childNode", c_node);  
				childMenu.add(jsonMenu);  
			}
		}
		logger.info("-- end OmsLoginServiceImpl.treeMenuList--"+System.currentTimeMillis());
		return childMenu;  
	}

	private JSONArray getTopMenu(String customerId){
		logger.info("-- begin OmsLoginServiceImpl.getTopMenu--"+System.currentTimeMillis());
		JSONArray jsonArray = new JSONArray();
		String rightsStr = Redis.use("users").get("am_"+customerId);
		if(!StringUtils.isBlank(rightsStr)){
			try {
				JSONArray arry = JSONArray.parseArray(rightsStr);
				for (int i = 0; i < arry.size(); i++) {
					JSONObject jsonObject = (JSONObject) arry.get(i);
					if(jsonObject.get("pid").toString().equals("0")){
						jsonArray.add(arry.get(i));
					}
				}
			} catch (Exception e) {
				logger.error("-- in OmsLoginServiceImpl.getTopMenu，errorCode:4015100107,获取缓存一级菜单信息错误:"+e);
			}
		}else{
			logger.info("-- in OmsLoginServiceImpl.getTopMenu,4015100108-从缓存中获取不到该用户的菜单信息");
		}
		logger.info("-- end OmsLoginServiceImpl.getTopMenu--"+System.currentTimeMillis());
		return jsonArray;
	}

	//从所有的权限里面过滤出菜单信息
	private List<RightModel> getMenuFromRightList(List<RightModel> rightsList){
		logger.info("-- begin OmsLoginServiceImpl.getMenuFromRightList--"+System.currentTimeMillis());
		List<RightModel> result = new ArrayList<RightModel>();
		for(RightModel dto:rightsList){
			if(dto.getInt("routeType")==0){
				result.add(dto);
			}
		}
		logger.info("-- end OmsLoginServiceImpl.getMenuFromRightList--"+System.currentTimeMillis());
		return result;
	}

	/**
	 * 从角色列表信息过滤角色id列表
	 * @param roleList
	 * @return
	 */
	private List<Integer> getRoleIdList(List<RoleModel> roleList){
		List<Integer> roleIdList = new ArrayList<Integer>();
		if(null != roleList && roleList.size() > 0){
			for(int i = 0; i<roleList.size();i++){
				RoleModel role = roleList.get(i);
				roleIdList.add(role.getInt("roleId"));
			}
		}
		return roleIdList;
	}

	@Override
	public Map<String, Object> userList(Map<String, Object> params) {
		logger.info("-- begin UserServiceImpl.userList,params{}",params);
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try {
			String name = params.get("name") == null ? "" : params.get("name").toString();
			String mobileNo = params.get("mobileNo") == null ? "" : params.get("mobileNo").toString();
			String pageNum = params.get("pageNum") == null ? "1" : params.get("pageNum").toString();
			String pageSize = params.get("pageSize") == null ? "20" : params.get("pageSize").toString();
			StringBuffer sql = new StringBuffer("FROM oms_account_main where 1 = 1");
			if(!StringUtils.isBlank(name)){
				sql.append(" and user_name ='"+name+"'");
			}
			if(!StringUtils.isBlank(mobileNo)){
				sql.append(" and mobile_no ='"+mobileNo+"'");
			}
			
			Page<UserAccountModel> userPage = UserAccountModel.me.paginate(Integer.parseInt(pageNum),Integer.parseInt(pageSize),"SELECT * ",sql.toString());
			Map<String, Object> userPageMap = new HashMap<String,Object>();
			userPageMap.put("userList", userPage.getList());
			userPageMap.put("totalPage", userPage.getTotalPage());
			userPageMap.put("pageNum", userPage.getPageNumber());
			userPageMap.put("pageSize", userPage.getPageSize());
			userPageMap.put("totalRow", userPage.getTotalRow());
			resultMap.put("code", Constants.SUCCESS_CODE);
			resultMap.put("msg", Constants.SUCCESS_MSG);
			resultMap.put("data", userPageMap);
		} catch (Exception e) {
			logger.error("-- error UserServiceImpl.userList,Exception{}",e);
			resultMap.put("code", "100301");
			resultMap.put("msg", "获取用户列表失败");
		}
		logger.info("-- end UserServiceImpl.userList==========================");
		return resultMap;
	}

	@Override
	public Map<String, Object> userDetail(Map<String, Object> params) {
		logger.info("-- begin UserServiceImpl.userDetail,params{}",params);
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try {
			String userId = params.get("userId") == null ? "" : params.get("userId").toString();
			logger.info("-- in UserServiceImpl.userDetail,uesrId=={}",userId);
			UserAccountModel userDetail = UserAccountModel.me.findById(userId);
			logger.info("-- in UserServiceImpl.userDetail,userDetail{}",userDetail);
			Map<String, Object> userMap = new HashMap<String,Object>();
			userMap.put("userDetail", userDetail);
			resultMap.put("code", Constants.SUCCESS_CODE);
			resultMap.put("msg", Constants.SUCCESS_MSG);
			resultMap.put("data", userMap);
		} catch (Exception e) {
			logger.error("-- error UserServiceImpl.userDetail,Exception{}",e);
			resultMap.put("code", "100401");
			resultMap.put("msg", "获取用户详情失败");
		}
		logger.info("-- end UserServiceImpl.userDetail==========================");
		return resultMap;	
	}

	@Override
	public Map<String, Object> userEdit(Map<String, Object> params) {
		logger.info("begin UserServiceImpl.userEdit,params{}",params);
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try {
			
			String customerId = params.get("customerId") == null ? "" : params.get("customerId").toString();
			String name = params.get("name") == null ? "" : params.get("name").toString();
			String mobileNo = params.get("mobileNo") == null ? "" : params.get("mobileNo").toString();
			String sex = params.get("sex") == null ? "" : params.get("sex").toString();
			String contactNo = params.get("contactNo") == null ? "" : params.get("contactNo").toString();
			String email = params.get("email") == null ? "" : params.get("email").toString();
			String birthday = (String) params.get("birthday") == null ? "" : params.get("birthday").toString();
			Date date = new Date();
			if(StringUtils.isEmpty(birthday)){
				date = null;
				 
			}else{
				date = new SimpleDateFormat("yyyy-MM-dd").parse(birthday); 
			}
			String updateId = params.get("updateId") == null ? "" : params.get("updateId").toString();
			String userId = params.get("userId") == null ? "" : params.get("userId").toString();
			boolean flag = UserAccountModel.me.findById(userId)
			.set("user_name", name)
			.set("contact_no", contactNo)
			.set("mobile_no", mobileNo)
			.set("sex", sex)
			.set("email", email)
			.set("birthday", date)
			.set("update_id", updateId)
			.set("update_date", new Date())
			.update();
			resultMap.put("code", Constants.SUCCESS_CODE);
			resultMap.put("msg", Constants.SUCCESS_MSG);
		} catch (Exception e) {
			logger.error("-- error UserServiceImpl.userEdit,Exception{}",e);
			resultMap.put("code", "100501");
			resultMap.put("msg", "编辑用户信息失败");
		}
		logger.info("-- end UserServiceImpl.userEdit==========================");
		return resultMap;
	}

	@Override
	public Map<String, Object> userAdd(Map<String, Object> params) {
		logger.info("-- begin UserServiceImpl.userAdd,params{}",params);
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try {
			String accountNo = params.get("accountNo") == null ? "" : params.get("accountNo").toString();
			String password = params.get("password") == null ? "" : params.get("password").toString();
			String contactNo = params.get("contactNo") == null ? "" : params.get("contactNo").toString();
			String mobileNo = params.get("mobileNo") == null ? "" : params.get("mobileNo").toString();
			String userName = params.get("userName") == null ? "" : params.get("userName").toString();
			String sex = params.get("sex") == null ? "" : params.get("sex").toString();
			String idType = params.get("idType") == null ? "" : params.get("idType").toString();
			String idNo = params.get("idNo") == null ? "" : params.get("idNo").toString();
			String birthday = params.get("birthday") == null ? "" : params.get("birthday").toString();
			Date date = new Date();
			if(!StringUtils.isEmpty(birthday)){
				 date = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
			}else{
				date = null;
			}
			String email = params.get("email") == null ? "" : params.get("email").toString();
			String createId = params.get("createId") == null ? "" : params.get("createId").toString();
			UserAccountModel userAccount = new UserAccountModel();
			boolean flag = userAccount.set("customer_id", CustomerIDUtil.getCustomerId())
					.set("account_no", accountNo)
					.set("password", password)
					.set("contact_no", contactNo)
					.set("mobile_no", mobileNo)
					.set("user_name", userName)
					.set("sex", sex)
					.set("id_type", idType)
					.set("id_no",idNo)
					.set("birthday",date)
					.set("email",email)
					.set("create_date", new Date())
					.set("create_id",createId)
					.set("update_id",createId)
					.save();
			int id = userAccount.getInt("id");
			boolean flagU = new UserRoleCfgModel()
					.set("user_id",id)
					.set("role_id", 2)
					.set("create_id", id)
					.set("update_id", id)
					.save();
			resultMap.put("code", Constants.SUCCESS_CODE);
			resultMap.put("msg", Constants.SUCCESS_MSG);
		} catch (Exception e) {
			logger.error("-- error UserServiceImpl.userEdit,Exception{}",e);
			resultMap.put("code", "100701");
			resultMap.put("msg", "新增用户信息失败");
		}
		logger.info("-- end UserServiceImpl.userAdd,params{}");
		return resultMap;
	}

	@Override
	public Map<String, Object> userDelete(Map<String, Object> params) {
		logger.info("-- begin UserServiceImpl.userDelete,params{}",params);
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try {
			String userId = params.get("userId") == null ? "" : params.get("userId").toString();
			//int countNum = Db.update("update oms_account_main set status = ? where customer_id = ?", "N",customerId);
			boolean flag = UserAccountModel.me.deleteById(userId);
			resultMap.put("code", Constants.SUCCESS_CODE);
			resultMap.put("msg", Constants.SUCCESS_MSG);
		} catch (Exception e) {
			logger.error("-- error UserServiceImpl.userDelete,Exception{}",e);
			resultMap.put("code", "100601");
			resultMap.put("msg", "删除用户失败");
		}
		logger.info("-- end UserServiceImpl.userDelete==========================");
		return resultMap;	
	}
}
